package com.company.cloud.customer.modules.app.controller;

import java.util.Date;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.json.JSONUtil;
import com.company.cloud.common.cache.CacheService;
import com.company.cloud.common.redis.service.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.bean.BaseParam;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.bean.LoginUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.constant.BaseConstant.YNEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.customer.modules.app.controller.req.AddrSaveParam;
import com.company.cloud.customer.modules.app.controller.req.AddrUpdateParam;
import com.company.cloud.customer.modules.base.entity.CustomerAddrInfo;
import com.company.cloud.customer.modules.base.service.CustomerAddrInfoService;
import com.company.cloud.customer.modules.cache.models.AddrModel;
import com.company.cloud.customer.modules.cache.utils.CustomerConvertUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;

@Login
@RestController
@RequestMapping("/app/cust/addr")
@Api(tags="Cust_App_客户收货地址服务")
@Slf4j
public class AddrInfoController {
	
	@Autowired
	private CustomerAddrInfoService customerAddrInfoService;

	@Autowired
	private RedisUtils redisUtils;
	
	@GetMapping("/list")
	@ApiOperation(value="客户收货地址列表", response=AddrModel.class)
	public BaseResult list(BaseParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo =AuthContextUtils.getUser();
		List<CustomerAddrInfo> addrList= customerAddrInfoService.list(new QueryWrapper<CustomerAddrInfo>()
				.eq("rows_state",EnabledEnum.ENABLED.getCode())
				.eq("user_id", userInfo.getId())
				.orderByDesc("cdt")
				);
		if(CollectionUtils.isEmpty(addrList)) {
			return BaseResult.ok();
		}
		List<AddrModel> data= addrList.stream().map(new Function<CustomerAddrInfo, AddrModel>() {
			@Override
			public AddrModel apply(CustomerAddrInfo entity) {
				return CustomerConvertUtils.getAddrModel(entity);
			}
		}).collect(Collectors.toList());
		return BaseResult.ok(data);
	}


	@GetMapping("/getDef")
	@ApiOperation(value="客户默认收货地址详情",response =AddrModel.class )
	public BaseResult getDef() {
		LoginSimpleUserInfo userInfo =AuthContextUtils.getUser();
		CustomerAddrInfo result =customerAddrInfoService.getOne(
				new QueryWrapper<CustomerAddrInfo>()
						.eq("is_def", YNEnum.YES.getCode())
						.eq("rows_state",EnabledEnum.ENABLED.getCode())
						.eq("user_id", userInfo.getId())
		);
		if(result==null){
			return BaseResult.ok();
		}
		AddrModel data=CustomerConvertUtils.getAddrModel(result);
		return BaseResult.ok(data);
	}

	
	@GetMapping("/get")
	@ApiOperation(value="客户收货地址详情",response =AddrModel.class )
	public BaseResult get(@RequestParam("id")Integer id, HttpServletRequest request) {
		CustomerAddrInfo result = customerAddrInfoService.getById(id);
		if(result==null || EnabledEnum.DISABLED.getCode().equals(result.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		// 登录人用户信息的获取方式
		//String token = request.getHeader("token");
		//String userid = request.getHeader("userid");
		//String userId = request.getHeader("userId");// userid == userId
		//String userHeader = request.getHeader("userHeader");
		//String redisTokenVal = redisUtils.get(token);
		//log.info("token: {}, userid: {}, redisTokenVal: {}, userHeader: {}, userId: {}",
		//		token, userid, redisTokenVal, userHeader, userId);'
		// token: AUK_1852724408934862848, userid: 28244, redisTokenVal: {"companyNo":"PTC","dataAuthorityScope":[],"headImg":"https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132","id":28244,"ip":"139.227.2.82","isDeptManager":"0","isManager":"0","jobCode":[],"key":"57fdc7abd3b84f73aced2c630d923bd5","langType":"ZH","mobile":"18964643995","nationCode":"86","nickName":"微信用户","nullDefVal":"-","shareCode":"1852724408905637888","sourceOne":"1","thirdId":4701,"thirdOpenId":"ochTJ5ZspwP5_ApP45r2YEgkFzto","thirdSessionKey":"4zvDL8vAlRuZr0IjKYPq+A==","thirdUserId":-1,"token":"AUK_1852724408934862848","userName":"ochTJ5ZspwP5_ApP45r2YEgkFzto","userState":"1","userTags":[],"userTypeOne":"2"}, userHeader: MjgyNDR8UFRDfG9jaFRKNVpzcHdQNV9BcFA0NXIyWUVna0Z6dG98MnwtfDQ3MDF8LTF8b2NoVEo1WnNwd1A1X0FwUDQ1cjJZRWdrRnp0b3wzNi4xMTIuMTg3Ljc5fEFVS18xODUyNzI0NDA4OTM0ODYyODQ4fC18LXwtfDJmMGI1ZTNhODFhMzQyNmJiYWQyYTdhMDdkZDYyMTQy, userId: 28244
		//if (StringUtils.isNotBlank(redisTokenVal)) {
		//	LoginUserInfo loginUserInfo = JSONUtil.toBean(redisTokenVal, LoginUserInfo.class);
		//}

		//用户ID校验
		LoginSimpleUserInfo userInfo =AuthContextUtils.getUser();
		if (!result.getUserId().equals(userInfo.getId())){
			throw new BusinessException(BaseReturnEnum.NOT_AUTHC);
		}
		AddrModel data=CustomerConvertUtils.getAddrModel(result);
		return BaseResult.ok(data);
	}


	
	@PostMapping("/save")
	@ApiOperation(value="客户收货地址新增")
	public BaseResult save(@RequestBody AddrSaveParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo =AuthContextUtils.getUser();
		CustomerAddrInfo addrInfo=new CustomerAddrInfo();
		BeanUtils.copyProperties(params, addrInfo);
		addrInfo.setCompanyNo(userInfo.getCompanyNo());
		addrInfo.setUserId(userInfo.getId());
		addrInfo.setRowFlag(new Date().getTime());
		addrInfo.setRowsState(EnabledEnum.ENABLED.getCode());
		addrInfo.addCreateParam(userInfo);
		customerAddrInfoService.save(addrInfo);
		
		if(YNEnum.YES.getCode().equals(addrInfo.getIsDef())) {
			CustomerAddrInfo addr2=new CustomerAddrInfo();
			addr2.setIsDef(YNEnum.NO.getCode());
			customerAddrInfoService.update(addr2,new UpdateWrapper<CustomerAddrInfo>()
					.eq("user_id", userInfo.getId())
					.ne("id", addrInfo.getId())
					);
		}
		return BaseResult.ok();
	}
	
	@PostMapping("/update")
	@ApiOperation(value="客户收货地址修改")
	public BaseResult update(@RequestBody AddrUpdateParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo =AuthContextUtils.getUser();
		CustomerAddrInfo addrInfo = customerAddrInfoService.getById(params.getId());
		if(addrInfo==null || EnabledEnum.DISABLED.getCode().equals(addrInfo.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		BeanUtils.copyProperties(params, addrInfo);
		addrInfo.setRowFlag(new Date().getTime());
		addrInfo.addEditParam(userInfo);
		customerAddrInfoService.updateById(addrInfo);
		
		if(YNEnum.YES.getCode().equals(addrInfo.getIsDef())) {
			customerAddrInfoService.update(new UpdateWrapper<CustomerAddrInfo>()
					.set("is_def", YNEnum.NO.getCode())
					.eq("user_id", userInfo.getId())
					.ne("id", addrInfo.getId())
					);
		}
		
		return BaseResult.ok();
	}
	
	@GetMapping("/settingDef")
	@ApiOperation(value="客户默认地址设置")
	public BaseResult settingDef(@RequestParam("id")Integer id) {
		LoginSimpleUserInfo userInfo =AuthContextUtils.getUser();
		CustomerAddrInfo addrInfo = customerAddrInfoService.getById(id);
		if(addrInfo==null || EnabledEnum.DISABLED.getCode().equals(addrInfo.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		addrInfo.setIsDef(YNEnum.YES.getCode());
		addrInfo.addEditParam(userInfo);
		customerAddrInfoService.updateById(addrInfo);
		
		CustomerAddrInfo addr2=new CustomerAddrInfo();
		addr2.setIsDef(YNEnum.NO.getCode());
		customerAddrInfoService.update(addr2,new UpdateWrapper<CustomerAddrInfo>()
				.eq("user_id", userInfo.getId())
				.ne("id", addrInfo.getId())
				);
		return BaseResult.ok();
	}
	
	
	@GetMapping("/delete")
	@ApiOperation(value="客户收货地址删除")
	public BaseResult delete(@RequestParam("id")Integer id) {
		LoginSimpleUserInfo userInfo =AuthContextUtils.getUser();
		CustomerAddrInfo addrInfo = customerAddrInfoService.getById(id);
		if(addrInfo==null || EnabledEnum.DISABLED.getCode().equals(addrInfo.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		addrInfo.setRowsState(EnabledEnum.DISABLED.getCode());
		addrInfo.addEditParam(userInfo);
		customerAddrInfoService.updateById(addrInfo);
		return BaseResult.ok();
	}
	

}
